﻿using System;
using System.Data.SqlTypes;
using System.Data.SqlClient;

public partial class StoredProcedures
{
	[Microsoft.SqlServer.Server.SqlProcedure]
	public static void ModifyTag(SqlString StationID,SqlString Caster,
		SqlString FromTag,SqlString ToTag)
	{
		if (!CheckString(StationID) ||
			!CheckString(Caster) ||
			!CheckString(FromTag) ||
			!CheckString(ToTag))
		{
			return;
		}

		if (FromTag == ToTag)
		{
			return;
		}

		using (SqlConnection con = new SqlConnection("context connection=true"))
		{
			con.Open();
			using (CommandSet cmd = new CommandSet(con.CreateCommand(), StationID, Caster, FromTag))
			{
				cmd.CommandText = "EXECUTE dbo.ReleaseBind @lid,@tid;";
				cmd.ExecuteNonQuery();

				cmd.CommandText = "SELECT dbo.GetBindedTagsCount(@lid);";
				int cnt = (int)cmd.ExecuteScalar();

				if (cnt >= MaxTagsCount)
				{
					cmd.CommandText = "EXECUTE dbo.LastValueReleaseBind @lid;";
					cmd.ExecuteNonQuery();
				}
				cmd.GetTagsId(ToTag);
				cmd.CommandText = "EXECUTE dbo.RegistBind @lid,@tid;";
				cmd.ExecuteNonQuery();
			}
		}

	}
};
